function renamedicom(dcmfile, pattern)
% renamedicom  - rename a dicom file according to a pattern
%
% FORMAT:       renamedicom(dcmfile, pattern)
%
% Input fields:
%
%       dcmfile     dicom filename
%       pattern     1xN cell string of key names or tag numbers
%
% No output fields

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
   ~ischar(dcmfile) || ...
    isempty(dcmfile) || ...
    exist(dcmfile, 'file') ~= 2
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing dicom filename.' ...
    );
end

% try to read dicom file
try
    dcmobj = dcmio(dcmfile);
    if length(dcmobj.DataKeys) < 10
        error('BAD_DICOM_FILE');
    end
catch
    error( ...
        'BVQXtools:BadArgument', ...
        'Probably no DICOM file or not supported yet.' ...
    );
end

% pattern given?
if nargin < 2 || ...
   ~iscell(pattern) || ...
    isempty(pattern)
    pattern = { ...
        'SeriesDescription', ...
        {'%s', 'SeriesDate'}, ...
        {'%s', 'SeriesTime'}, ...
        {'ser%04d', 'SeriesNumber', 'd'}, ...
        {'ins%04d', 'InstanceNumber', 'd'}, ...
        {'itm%04d', 'ItemNumber', 'd'} ...
    };
end

% build new filename
[newfile{1:3}] = fileparts(dcmfile);
newfname = '';
for pc = 1:length(pattern)
    if ~isempty(newfname)
        newfname(end+1) = '_';
    end
    if ischar(pattern{pc})
        try
            newfname = [newfname, makelabel(dcmobj.Value(pattern{pc}))];
        catch
            % nothing
        end
    elseif iscell(pattern{pc})
        if numel(pattern{pc}) > 1 && ...
           ~isempty(pattern{pc}{2})
            try
                if numel(pattern{pc}) > 2
                    newfname = [newfname, sprintf(pattern{pc}{1}, ...
                        str2double(dcmobj.Value(pattern{pc}{2})))];
                else
                    newfname = [newfname, sprintf(pattern{pc}{1}, ...
                        dcmobj.Value(pattern{pc}{2}))];
                end
            catch
                % nothing
            end
        end
    end
end

% rename file
newfile = [newfile{1} filesep newfname newfile{3}];
if ~strcmpi(newfile, dcmfile)
    if exist(newfile, 'file') == 2

        % test existing object for crucial elements
        objdiff = false;
        try
            exsobj = dcmio(newfile);
            exsimg = exsobj.PixelData;
            newimg = dcmobj.PixelData;
            if length(exsimg) ~= length(newimg) || ...
                any(exsimg ~= newimg)
                objdiff = true;
            end
        catch
            error( ...
                'BVQXtools:BadFileContent', ...
                'Error reading comparison file ''%s''.', ...
                newfile ...
            );
        end

        % so now, bail out?
        if objdiff
            error( ...
                'BVQXtools:ConflictingFiles', ...
                'Conflicting files found. Not renaming ''%s'' to ''%s''.', ...
                dcmfile, newfile ...
            );
        end
    end

    % then rename
    movefile(dcmfile, newfile);
end

